<template>
  <div class="map-base_map">
    <div class="base_map-group">
      <el-button-group>
        <template v-for="(item, index) in layers" :key="item.name">
          <el-button :type="index === currentIndex ? 'primary' : 'default'" @click="changeIndex(index)">
            {{ item.name }}
          </el-button>
        </template>
      </el-button-group>
    </div>
    <div class="base_map-card"></div>
  </div>
</template>

<script lang="ts" setup>
import { type PropType, ref } from 'vue';
import type { LayerOtions } from '../../utils/layers';
import { createLayers } from '../../utils/layers';
import { useInjectMap } from '../../hooks/use-inject-map';

defineOptions({
  name: 'BaseMap',
});

const defaultLayers: LayerOtions[] = [
  {
    type: 1,
    name: '矢量地图',
    options: {
      url: 'http://t0.tianditu.com/DataServer?T=vec_c&x={x}&y={y}&l={z}',
    },
  },
  {
    type: 1,
    name: '影像地图',
    options: {
      url: 'http://t0.tianditu.com/DataServer?T=img_c&x={x}&y={y}&l={z}',
    },
  },
  {
    type: 1,
    name: '地形地图',
    options: {
      url: 'http://t0.tianditu.com/DataServer?T=ter_c&x={x}&y={y}&l={z}',
    },
  },
];

const { map } = useInjectMap();

const props = defineProps({
  baseLayers: {
    type: Array as PropType<LayerOtions[]>,
  },
  type: {
    type: String,
    default: 'tabs',
    validator: (val: string) => ['tabs', 'card'].includes(val),
  },
  active: {
    type: [String, Number],
  },
});

const currentIndex = ref(0);
const layers = props.baseLayers || defaultLayers;

const changeIndex = (index: number) => {
  currentIndex.value = index;
  removeLayer();
  addLayer();
};

const removeLayer = () => {
  const mapLayers = map?.getLayers();
  mapLayers?.removeAt(0);
};

const addLayer = () => {
  const layer = createLayers({
    key: 'baseLayer',
    ...layers[currentIndex.value],
  });
  const mapLayers = map?.getLayers();
  mapLayers?.insertAt(0, layer);
};

addLayer();
</script>
